import React from "react"

export function useLoading() {

    const [sum, setSum] = React.useState(0)

    const loading = React.useMemo(() => sum > 0, [sum]);

    const run = React.useCallback(async (fun: () => Promise<void>, reject?: (error: any) => void) => {
        try {
            setSum(e => e + 1)
            await fun()
        } catch (error) {
            reject?.(error);
        } finally {
            setSum(e => e - 1)
        }
    }, [])

    return { loading, run }
}